package com.cw.jeeyt.service.impl.security;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cw.jeeyt.common.enums.EnumPermissionAssignType;
import com.cw.jeeyt.service.bo.security.SecurityRoleResourceBo;
import com.cw.jeeyt.service.intf.security.SecurityResourceService;
import com.cw.jeeyt.service.intf.security.SecurityRoleResourceService;
import com.cw.jeeyt.service.intf.security.SecurityService;
import com.cw.lang.common.utils.SequenceTool;

/**
 * 数据权限业务实现类
 *
* @author chenw
* @version 1.0.0
 */
@Service
public class SecurityServiceImpl implements SecurityService {
    @Autowired
    private SecurityRoleResourceService securityRoleResourceService;
    @Autowired
    private SecurityResourceService securityResourceService;

    /**
     * 分配资源信息
     */
    @Override
    public void assignSecurity(String ids, Long assignId, String type) throws Exception {
        String[] idList = ids.split(",");
        //如果存在，则跳过，如果页面删除了权限则需删除对应的记录
        if (EnumPermissionAssignType.ROLE.getCode()
            .equals(type)) {
            List<SecurityRoleResourceBo> roleResourceList = securityRoleResourceService.queryRoleResourceByRoleId(
                assignId);
            if (roleResourceList != null && !roleResourceList.isEmpty()) {
                for (SecurityRoleResourceBo roleResourceBo : roleResourceList) {
                    String resId = String.valueOf(roleResourceBo.getResId());
                    if (!ids.contains(resId)) {
                        securityRoleResourceService.delete(roleResourceBo);
                    }
                }
            }
            for (String resId : idList) {
                SecurityRoleResourceBo securityRoleResource = securityRoleResourceService.getByRoleIdAndResId(assignId,
                    Long.parseLong(resId));
                if (securityRoleResource != null) {
                    continue;
                }
                SecurityRoleResourceBo securityRoleResourceBo = new SecurityRoleResourceBo();
                String id = SequenceTool.nextId();
                securityRoleResourceBo.setId(id);
                securityRoleResourceBo.setRoleId(assignId);
                securityRoleResourceBo.setResId(Long.parseLong(resId));

                securityRoleResourceService.insert(securityRoleResourceBo);
            }
        }else {
            throw new Exception("没有找到分配权限的类型");
        }
        //权限分配成功以后，需要将redis中的资源权限缓存重新初始化一次
        securityResourceService.refreshSecurityResource();
    }
}
